package sunwin.yoms.service.resource;

import com.github.pagehelper.PageHelper;
import jodd.datetime.JDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.UnexpectedRollbackException;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.comm.YomsPage;
import sunwin.yoms.comm.model.TimeSpan;
import sunwin.yoms.dao.SubscribeExceptionDao;
import sunwin.yoms.domain.resource.SubscribeExceptionDomain;
import sunwin.yoms.service.rmiServer.ISubscribeOrder;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by watson on 2015/11/27.
 */
@Service
public class SubscribeExceptionService {
    @Autowired
    private SubscribeExceptionDao subscribeExceptionDao;
    @Autowired
    private StadiumService stadiumService;
    @Autowired
    private ISubscribeOrder iSubscribeOrder;
    @Autowired
    JmsTemplate jmsTemplate;


    /**
     * 查找预约例外表展示
     *
     * @param domain
     * @return
     * @throws YomsException
     */
    public List<SubscribeExceptionDomain> getExceptionList(SubscribeExceptionDomain domain, YomsPage yomsPage) throws YomsException, ParseException {
        com.github.pagehelper.Page total = PageHelper.startPage(yomsPage.getPageIndex(), yomsPage.getPageSize(), true);
        List<SubscribeExceptionDomain> domains = subscribeExceptionDao.getDomainCollection(domain);
        yomsPage.setPageCount(total.getTotal() % yomsPage.getPageSize() == 0 ? total.getTotal() / yomsPage.getPageSize() : total.getTotal() / yomsPage.getPageSize() + 1);
        if (domains.size() == 0) {
            throw new YomsException("未找到数据");
        } else {
            Date dt = new Date();
            SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
            String curDateString = matter1.format(dt);
            DateFormat df = DateFormat.getDateInstance();
            Date curDate = df.parse(curDateString);
            for (int i = 0; i < domains.size(); i++) {
                if (domains.get(i).getExceptionDate().before(curDate)) {
                    domains.get(i).setExceptionPass(2);
                    subscribeExceptionDao.updateDomain(domains.get(i));
                } else {
                    domains.get(i).setExceptionPass(1);
                    subscribeExceptionDao.updateDomain(domains.get(i));
                }
            }
            return domains;
        }
    }

    /**
     * 根据domain条件查询场馆
     */
    public SubscribeExceptionDomain getSubExceptionDamain(SubscribeExceptionDomain domain) throws YomsException {
        List<SubscribeExceptionDomain> domains = subscribeExceptionDao.getDomainByCondition(domain);
        if (domains.size() > 1) {
            throw new YomsException("该场馆计划重复");
        } else if (domains.size() == 0) {
            return new SubscribeExceptionDomain();
        } else {
            return domains.get(0);
        }

    }

    /**
     * 增加例外表
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void addSubException(SubscribeExceptionDomain domain) throws Exception {
        domain.setExceptionCreateTime(new JDateTime(System.currentTimeMillis()).convertToDate());
        SubscribeExceptionDomain domain1 = new SubscribeExceptionDomain();
        domain1.setStadiumId(domain.getStadiumId());
        domain1.setExceptionDate(domain.getExceptionDate());
        List<SubscribeExceptionDomain> domains = subscribeExceptionDao.getDomainByCondition(domain1);
        if (domains.size() > 0) {
            throw new YomsException("该场馆日期内已有计划，不能重复增加");
        } else {
            subscribeExceptionDao.addDomain(domain);
            try {
                iSubscribeOrder.cancelSubscribe(domain.getStadiumId(), domain.getExceptionDate(), domain.getExceptionTimeBucket());
                /*//将取消场馆预约的消息放入队列
                jmsTemplate.send("CancelOrder", new MessageCreator() {
                    @Override
                    public Message createMessage(Session session) throws JMSException {
                        return session.createObjectMessage("你的预约订单已取消,详情请上官方网站查询");
                    }
                });*/
            } catch (Exception e) {
                throw new UnexpectedRollbackException("删除预约订单失败");
            }
        }
    }

    /**
     * 更新例外计划
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void updateSubException(SubscribeExceptionDomain domain) throws YomsException {
        SubscribeExceptionDomain domain1 = subscribeExceptionDao.getDomainById(domain.getExeptionId());
        if (domain1 == null) {
            throw new YomsException("该数据不存在");
        } else {
            //从数据库中取得日期数据
            domain.setExceptionDate(domain1.getExceptionDate());
            domain.setStadiumId(domain1.getStadiumId());
            domain.setExceptionContent(domain1.getExceptionContent());
            subscribeExceptionDao.updateDomain(domain);
            try {
                iSubscribeOrder.cancelSubscribe(domain.getStadiumId(), domain.getExceptionDate(), domain.getExceptionTimeBucket());
            } catch (Exception e) {
                throw new UnexpectedRollbackException("删除预约订单失败");
            }
        }
    }

    /**
     * 删除例外计划
     */
    public void delSubException(int id) throws YomsException {
        SubscribeExceptionDomain domain = subscribeExceptionDao.getDomainById(id);
        if (domain == null) {
            throw new YomsException("数据不存在");
        } else {
            subscribeExceptionDao.deleteDomain(domain);
        }
    }

    /**
     * 根据ID查找例外
     */
    public SubscribeExceptionDomain getSubExceptionById(int id) throws YomsException {
        SubscribeExceptionDomain domain = subscribeExceptionDao.getDomainById(id);
        return domain;
    }

    /**
     * 根据SID查找例外时间值
     */
    public long getSubExcepedTimeById(int sid, Date date) throws YomsException {
        SubscribeExceptionDomain domain1 = new SubscribeExceptionDomain();
        domain1.setStadiumId(sid);
        domain1.setExceptionDate(date);
        List<SubscribeExceptionDomain> domains = subscribeExceptionDao.getDomainByCondition(domain1);
        long SubExceptionValue = domains.get(0).getExceptionTimeBucket();
        return SubExceptionValue;
    }

    /**
     * 根据条件查找domain
     */
    public SubscribeExceptionDomain getSubExceptionByCondition(int sid) throws YomsException {
        SubscribeExceptionDomain domain1 = new SubscribeExceptionDomain();
        domain1.setStadiumId(sid);
        List<SubscribeExceptionDomain> domains = subscribeExceptionDao.getDomainByCondition(domain1);
        if (domains.size() == 0) {
            throw new YomsException("数据不存在");
        }
        return domains.get(0);
    }

    /**
     * 根据场馆ID得到例外计划表
     */
    public List<SubscribeExceptionDomain> getSubExceptionBySid(int sid) throws YomsException {
        SubscribeExceptionDomain domain = new SubscribeExceptionDomain();
        domain.setStadiumId(sid);
        List<SubscribeExceptionDomain> domains = subscribeExceptionDao.getDomainCollection(domain);
        if (domains.size() == 0) {
            throw new YomsException("该场馆暂无例外计划");
        } else {
            return domains;
        }
    }

    /**
     * 将营业时间段划分成单位为一小时一段的集合
     *
     * @throws YomsException
     */
    public List<TimeSpan> businessHours(TimeSpan timeSpan) {
        List<TimeSpan> businessHours = new ArrayList<>();

        JDateTime iterateTime = new JDateTime(timeSpan.getStartTime());
        JDateTime endTime = new JDateTime(timeSpan.getEndTime());

        while (iterateTime.isBefore(endTime)) {
            TimeSpan tsm = new TimeSpan();
            tsm.setStartTime(iterateTime.convertToSqlTime());
            iterateTime = iterateTime.addHour(1);
            tsm.setEndTime(iterateTime.convertToSqlTime());

            businessHours.add(tsm);
        }

        return businessHours;
    }
}
